<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品编码" prop="goodsId">
            <el-input v-model="form.goodsId" placeholder="请输入商品编码后点击回车" style="width: 50%" @keyup.enter.native="getGoodsInfo" />
          </el-form-item>
          <el-form-item label="商品型号" prop="shareGoodsId">
            <el-select filterable remote placeholder="请输入商品关键字" @change="goodsChange" style="width: 50%"
                       v-model="form.shareGoodsId" :remote-method="getShareGoodsOptions">
              <el-option v-for="good in shareGoodsOptions"
                         :label="good.goodsName"
                         :value="good.goodsId" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="串号" prop="goodsSn">
          <!--       @blur="blurSelGoodsByGoodsSn"     -->
            <el-input v-model="form.goodsSn" placeholder="请输入串号" clearable
                      style="width: 50%" />
          </el-form-item>
          <el-form-item label="成色" prop="fineness">
            <el-select v-model="form.fineness" placeholder="请选择成色">
              <el-option v-for="item in qualityList" :label="item.qualityName" :value="item.qualityName" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>

      <el-form-item label="验机数据:" prop="testInfo" v-if="form.testInfo">
        <span>{{form.testInfo}}</span>
      </el-form-item>

      <el-tabs v-model="activeName" @tab-click="handleClick" v-show="form.shareGoodsId">
        <el-tab-pane label="黑名单" name="blacklist">
          <div style="padding: 20px">
            <blacklist :goods-info="form" :goods-sn="form.goodsSn" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="质检" name="spec">
<!--          <el-form-item v-for="specs in specsRadios" :label="specs.label" size="small">-->
<!--            <el-radio-group v-model="specs.selected">-->
<!--              <el-radio v-for="radio in specs.children"-->
<!--                        :label="radio.value" border class="radio-sty">{{radio.text}}</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->

          <div class="check-group-box">
            <div class="label">基本规格</div>
            <div class="check-box" v-for="specs in specsRadios" v-if="specs.children && specs.children.length > 0">
              <div class="check-label">{{specs.label}}</div>
              <div>
                <div
                  class="check-item"
                  :class="specs.selected === radio.value ? 'check-item-sel': ''"
                  v-for="radio in specs.children"
                  @click="radioSelClick(specs, radio.value)"
                >{{radio.text}}</div>
              </div>

              <el-button size="mini" type="danger" @click="radioSelClick(specs, null)" plain>清除</el-button>
            </div>
          </div>

          <div v-for="type in topicTypeList" class="check-group-box" v-if="type.list && type.list.length > 0">
            <div class="label">{{type.label}}</div>

            <div class="check-box" v-for="test in type.list" v-if="test.children && test.children.length > 0">
              <div class="check-label">{{test.label}}</div>
              <div>
                <div
                  class="check-item"
                  :class="test.selected === radio.value ? 'check-item-sel': ''"
                  v-for="radio in test.children"
                  @click="radioSelClick(test, radio.value)"
                >{{radio.text}}</div>
              </div>

              <div>
                <el-button size="mini" type="danger" @click="radioSelClick(test, null)" plain>清除</el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>

<!--        <el-tab-pane v-for="type in topicTypeList" :label="type.label" :name="type.value">-->
<!--          <el-form-item  v-for="test in type.list" :label="test.label" size="small">-->
<!--            <el-radio-group v-model="test.selected">-->
<!--              <el-radio-->
<!--                v-for="radio in test.children"-->
<!--                :label="radio.value"-->
<!--                border-->
<!--                class="radio-sty"-->
<!--              >{{radio.text}}</el-radio>-->
<!--            </el-radio-group>-->
<!--            <el-button size="mini" type="danger" @click="test.selected = null" plain>清除</el-button>-->
<!--          </el-form-item>-->
<!--        </el-tab-pane>-->
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {addGoodsRecord, getGoodsNormal, listGoods, testUpdateGoods} from "@/api/recovery/goods";
import {getShareGoods, listShareGoods} from "@/api/share/goods";
import {listTestValues} from "@/api/basic/testValues";
import {listSpecs} from "@/api/share/specs";
import {listValues} from "@/api/share/values";
import {listTestTitle} from "@/api/basic/testTitle";
import {strTranArray} from "@/utils/tran/shareUtils";
import Blacklist from "@/views/recovery/goods/componets/blacklist.vue";
import {listQuality} from "@/api/share/quality";

export default {
  name: "GoodsTest",
  components: {Blacklist},
  data() {
    return {
      activeName: 'blacklist',
      topicTypeList: [],
      qualityList: [],
      // 表单参数
      form: {
        goodsId: null,
        collectId: null,
        goodsName: null,
        goodsSn: null,
        shareGoodsId: null,
        specsIds: null,
        testValues: null,
        goodsStep: null,
        confirmStatus: null,
        remark: null,
        printing: null,
        testInfo: undefined,
        recordId: undefined,
        fineness: undefined
      },
      //规格内容
      specsValuesList: [],
      // 规格标题
      specsList: [],
      //验机选项内容
      testRadios: [],
      // 规格选项组
      specsRadios: [],
      //共享模块的商品信息
      shareGoodsOptions: [],
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: "编码不能为空", trigger: "blur" }
        ],
        goodsSn: [
          { required: true, message: "串号不能为空", trigger: "blur" }
        ],
        shareGoodsId: [
          { required: true, message: "商品型号不能为空", trigger: "blur" }
        ],
        fineness: [
          { required: true, message: "成色不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.reset();
    listTestValues({}).then(resp => {
      this.testValuesList = resp.rows;
    })

    this.getDicts("basic_test_title_topic_type").then(response => {
      this.topicTypeOptions = response.data;
    });

    listQuality({}).then(res => {
      this.qualityList = res.rows;
    })

    this.getSpecsAndValuesList();
  },
  methods: {
    radioSelClick(val, v) {
      this.$set(val, "selected", v);
      this.getSpecsIdsAndTestValues();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    getGoodsInfo() {
      getGoodsNormal(this.form.goodsId).then(response => {
        this.form = response.data;
        this.msgSuccess("数据导入成功，请进行质检操作!");
        //新增日志
        addGoodsRecord(1, this.form.goodsId).then(res => {
          this.form.recordId = res.data.id;
        })
        if(this.form.shareGoodsId != null) {
          this.goodsChange(this.form.shareGoodsId);
          getShareGoods(this.form.shareGoodsId).then(resp => {
            if(resp.data) {
              this.shareGoodsOptions = [];
              this.shareGoodsOptions.push(resp.data);
            }

          })
        }else {
          this.specsRadios = [];
          this.testRadios = [];
          this.topicTypeList = [];
        }
      });
    },
    getSelectRadioValue(arr, radios) {
      for(let i = 0; i < arr.length; i++) {
        for(let j = 0; j < radios.length; j++) {
          if(arr[i] === radios[j].value) {
            return arr[i];
          }
        }
      }
      return null;
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.$emit("submitRefresh");
    },
    /** 获取规格组 */
    async getSpecsAndValuesList() {
      await listSpecs({}).then(resp => {
        this.specsList = resp.rows;
      })
      await listValues({}).then(resp => {
        this.specsValuesList = resp.rows;
      })
    },
    /** 获取规格和验机报告选择结果*/
    getSpecsIdsAndTestValues() {
      let specsId = "";
      let printing = "";
      for(let i = 0; i < this.specsRadios.length; i++) {
        specsId += this.specsRadios[i].selected + ",";
        for(let j = 0; this.specsRadios[i].children.length; j++) {
          if(this.specsRadios[i].selected === this.specsRadios[i].children[j].value) {
            printing += this.specsRadios[i].children[j].text + " ";
            break;
          }
        }
      }
      this.form.specsIds = specsId.substring(0, specsId.length - 1);
      this.form.printing = printing.substring(0, printing.length - 1);

      let testValues = "";
      let testInfo = "";
      for(let i = 0; i < this.testRadios.length; i++) {
        if(this.testRadios[i].selected != null) {
          testValues += this.testRadios[i].selected + ",";
          this.testRadios[i].children.forEach(it => {
            if(it.value === this.testRadios[i].selected)
              testInfo += it.text + ",";
          })
        }
      }
      this.form.testValues = testValues.substring(0, testValues.length - 1);
      this.form.testInfo = testInfo.substring(0, testInfo.length - 1);
    },
    /** 提交按钮 */
    submitForm() {
      this.getSpecsIdsAndTestValues();
      this.$refs["form"].validate(valid => {
        if (valid) {
          testUpdateGoods(this.form).then(response => {
            this.msgSuccess("操作成功！");
            this.cancel();
          });
        }
      });
    },
    /** 共享模块商品信息 */
    getShareGoodsOptions(e) {
      listShareGoods({goodsName: e}).then(resp => {
        this.shareGoodsOptions = resp.rows;
      })
    },
    /** 商品型号选着事件 */
    goodsChange(e) {
      getShareGoods(e).then(resp => {
        if(!resp.data)
          return
        this.form.goodsName = resp.data.goodsName;
        let specsMap = JSON.parse(resp.data.specsMap);
        this.specsRadios = [];
        for(let i = 0; i < specsMap.length; i++) {
          let data = null;        //单选组
          let isNewTitle = true;  //是否新标题
          let j = 0;              //当前内容
          while (j < this.specsRadios.length) {
            if(this.specsRadios[j].key === specsMap[i][0]) {
              isNewTitle = false;
              break;
            }
            j++;
          }
          if(isNewTitle) {
            data = {
              label: this.specsTitleFormatter(specsMap[i][0]),
              key: specsMap[i][0],
              selected: specsMap[i][1],
              children: [{text: this.specsValuesFormatter(specsMap[i][1]),value: specsMap[i][1]}]
            }
            this.specsRadios.push(data);
          }else {
            this.specsRadios[j].children.push({text: this.specsValuesFormatter(specsMap[i][1]), value: specsMap[i][1]});
          }
        }
        this.getSpecsMapList(resp.data.typeId, resp.data.brandId);
      })
    },
    /** 规格内容格式*/
    specsValuesFormatter(valuesId) {
      for(let i = 0; i < this.specsValuesList.length; i++) {
        if (valuesId === this.specsValuesList[i].valuesId) {
          return this.specsValuesList[i].valuesName;
        }
      }
    },
    //验证串号是否存在
    blurSelGoodsByGoodsSn() {
      if(this.form.goodsSn == null) {
        return
      }
      listGoods({goodsSn: this.form.goodsSn}).then(resp => {
        if(resp.rows.length > 0) {
          this.$message({ showClose: true, message: "请注意，该串号在回收商品列表出现过！", type: "warning" });
        }
      })
    },
    /** 规格标题格式 */
    specsTitleFormatter(specsId) {
      for (let i = 0; i < this.specsList.length; i++) {
        if(specsId === this.specsList[i].specsId) {
          return this.specsList[i].specsName;
        }
      }
    },
    getTopicType() {
      let arr = [];
      this.topicTypeOptions.forEach(it => {
        let obj = {
          label: it.dictLabel,
          value: it.dictValue,
          list: []
        }
        arr.push(obj);
      })
      arr.push({
        label: '其它',
        value: null,
        list: []
      })

      arr.forEach(a => {
        this.testRadios.forEach((b,key) => {
          if(b.type === a.value) {
            a.list.push(b);
          }
        })
      })
      this.topicTypeList = arr;
    },
    /** 初始化选项 */
    initSpecsAndTest() {
      if(this.form.specsIds != null) {
        let specsArr = strTranArray(this.form.specsIds);
        for(let i = 0; i < this.specsRadios.length; i++) {
          let res = this.getSelectRadioValue(specsArr, this.specsRadios[i].children);
          if(res != null) {
            this.specsRadios[i].selected = res;
          }
        }

        if(this.form.testValues != null) {
          let testArr = strTranArray(this.form.testValues);
          for(let i = 0; i < this.testRadios.length; i++) {
            let res = this.getSelectRadioValue(testArr, this.testRadios[i].children);
            if(res != null) {
              this.testRadios[i].selected = res;
            }
          }
        }
      }
    },
    /** 获取验机选项 */
    async getSpecsMapList(typeId, brandId) {
      let titleList = [];
      let valuesList = [];
      let params = {
        typeIds : typeId,
        isApple : parseInt(brandId) === 1 || parseInt(brandId) === 2 ? null : 1
      }
      await listTestTitle(params).then(resp => {
        titleList = resp.rows;
      })
      await listTestValues({}).then(resp => {
        valuesList = resp.rows;
      })
      this.testRadios = [];
      for(let i = 0; i < titleList.length; i++) {
        let data = {
          label: titleList[i].titleName,
          type: titleList[i].topicType,
          selected: null,
          children: []
        }
        for(let j = 0; j < valuesList.length; j++) {
          if(titleList[i].titleId === valuesList[j].titleId) {
            let children = {text: valuesList[j].valuesName, value: valuesList[j].valuesId}
            data.children.push(children);
          }
        }
        this.testRadios.push(data);
      }
      this.initSpecsAndTest(); //初始化商品数据

      this.getTopicType();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        collectId: null,
        goodsName: null,
        goodsSn: null,
        shareGoodsId: null,
        specsIds: null,
        testValues: null,
        goodsStep: null,
        confirmStatus: null,
        remark: null,
        printing: null,
        testInfo: undefined
      };
      this.resetForm("form");
    },
  }
}
</script>

<style scoped>

.radio-sty {
  margin-right: 2px !important;
}
.el-table .bg_red {
  background-color: rgb(253, 226, 226);

}
.dialog-footer {
  margin: 30px;
  text-align: center;
}
.check-group-box {
  .label {
    font-weight: bold;
    font-size: 24px;
    margin-top: 10px;
  }
  .check-box {
    display: flex;
    margin-top: 10px;
    .check-label {
      font-size: 16px;
      color: #606266;
      font-weight: bold;
      width: 10%;
      padding: 0 10px;
    }
    .check-item {
      display: inline-block;
      color: #606266;
      border: 1px solid #DCDFE6;
      padding: 5px 10px;
      margin-right: 6px;
      font-size: 12px;
      border-radius: 5px;
      cursor: pointer;
      margin-bottom: 6px;
    }
    .check-item-sel {
      color: #409EFF;
      border: 1px solid #409EFF;
    }
  }
}
</style>
